const Router = require('koa-router');
const multer = require('@koa/multer');
const path = require('path');
const fs = require('fs');
const auth = require('../middlewares/auth');
const User = require('../models/user');

const router = new Router({ prefix: '/api/user' });

// 确保上传目录存在
const uploadDir = path.join(__dirname, '../public/uploads/avatars');
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}

// 配置 multer
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, uniqueSuffix + path.extname(file.originalname));
  }
});

const upload = multer({ 
  storage: storage,
  limits: {
    fileSize: 2 * 1024 * 1024 // 2MB
  },
  fileFilter: (req, file, cb) => {
    if (file.mimetype.startsWith('image/')) {
      cb(null, true);
    } else {
      cb(new Error('请上传图片文件'));
    }
  }
});

// 头像上传接口
// 添加 auth 中间件到头像上传路由
router.post('/avatar', auth, upload.single('avatar'), async (ctx) => {
  try {
    const file = ctx.request.file;
    if (!file) {
      ctx.status = 400;
      ctx.body = { ok: false, error: '请上传文件' };
      return;
    }

    // 生成访问URL
    const avatarUrl = `/uploads/avatars/${file.filename}`;

    // 从认证中间件获取用户ID
    const userId = ctx.state.user.id;
    await User.updateUserInfo(userId, { avatar: avatarUrl });

    ctx.body = {
      ok: true,
      avatarUrl
    };
  } catch (error) {
    console.error('上传头像失败:', error);
    ctx.status = 500;
    ctx.body = { ok: false, error: error.message || '上传失败' };
  }
});

// 添加更新用户信息路由
router.put('/profile', auth, async (ctx) => {
  try {
    const { nickname, phone } = ctx.request.body;
    const userId = ctx.state.user.id;

    // 更新用户信息
    await User.updateUserInfo(userId, { nickname, phone });

    ctx.body = {
      ok: true,
      user: {
        nickname,
        phone
      }
    };
  } catch (error) {
    console.error('更新用户信息失败:', error);
    ctx.status = 500;
    ctx.body = { ok: false, error: error.message || '更新失败' };
  }
});

// 添加手机号更新路由
router.put('/phone', auth, async (ctx) => {
  try {
    const { phone } = ctx.request.body;
    const userId = ctx.state.user.id;

    // 验证手机号格式
    if (!/^1[3-9]\d{9}$/.test(phone)) {
      ctx.status = 400;
      ctx.body = { ok: false, error: "手机号格式不正确" };
      return;
    }

    // 更新用户手机号
    await User.updateUserInfo(userId, { phone });

    ctx.body = {
      ok: true,
      msg: "手机号更新成功",
      data: { phone }
    };
  } catch (error) {
    console.error('更新手机号失败:', error);
    ctx.status = 500;
    ctx.body = { ok: false, error: error.message || '更新失败' };
  }
});

module.exports = router;